package cn.tedu.rtc.mqtt.config;

import cn.tedu.rtc.mqtt.model.ChannelName;
import cn.tedu.rtc.mqtt.model.MqttClientOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import javax.annotation.Resource;

/**
 * Client configuration for inbound messages.
 */
@Slf4j
@Configuration
@IntegrationComponentScan
public class MqttInboundConfiguration {

    @Autowired
    private MqttPahoClientFactory mqttClientFactory;// Spring Bean自动管理，MqttConfiguration类中的mqttClientFactory Bean对象自动注入

    @Resource(name = ChannelName.INBOUND)
    private MessageChannel inboundChannel;

    /**
     * Clients of inbound message channels.接收信息的通道的客户端
     * 监听 topic: sys/product/+/status 和 thing/product/+/requests
     *
     * @return
     */
    @Bean(name = "adapter")
    public MessageProducerSupport mqttInbound() {
        MqttClientOptions options = MqttConfiguration.getClientOptions();
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
                options.getClientId() + "_服务器接收消息", mqttClientFactory, options.getTopics().split(","));
        DefaultPahoMessageConverter converter = new DefaultPahoMessageConverter();
        // use byte types uniformly
        converter.setPayloadAsBytes(true);
        adapter.setConverter(converter);
        adapter.setQos(0);
        adapter.setOutputChannel(inboundChannel);
        return adapter;
    }

//    /**
//     * Define the channel to handle messages that print message in terminal.（不在这里打印，改为由InboundMessageRouter类打印，同时进行路由）
//     * @return
//     */
//    @Bean
//    @ServiceActivator(inputChannel = ChannelName.INBOUND)
//    public MessageHandler messageInboundHandler() {
//        return new MessageHandler() {
//            @Override
//            public void handleMessage(Message<?> message) throws MessagingException {
//                MessageHeaders headers = message.getHeaders();
//                String topic = headers.get(MqttHeaders.RECEIVED_TOPIC).toString();
//                Object qos = headers.get(MqttHeaders.QOS);
//                UUID id = headers.getId();
//                byte[] payload = (byte[])message.getPayload();
//                log.info("received topic :{} \n payload :{} \n qos :{} \n id :{}", topic, new String(payload), qos, id);
//            }
//        };
//    }

    /**
     * Define a default channel to handle messages that have no effect.
     * 接收到的消息如果不合法或者暂时未定义其用途，可以直接发送到Default通道，并打印消息内容
     *
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = ChannelName.DEFAULT)
    public MessageHandler defaultInboundHandler() {
        return message -> {
            log.info("The default channel does not handle messages." +
                    "\nTopic: " + message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC) +
                    "\nPayload: " + message.getPayload());
        };
    }
}
